package com.iot.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iot.core.JsonHelper;
import com.iot.core.LResult;
import com.iot.core.PageData;
import com.iot.mapper.Twarn_record_detailMapper;
import com.iot.pojo.*;
import com.iot.service.TdeviceService;
import com.iot.service.Tdevice_recordService;
import com.iot.service.Tnb_dev_jsonService;
import com.iot.service.Twarn_recordService;
import com.iot.util.CenterPointAndZoom;
import com.iot.util.Common;
import com.iot.util.MrecJG;
import com.iot.util.MrecJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/device/device/")
public class TDeviceController extends BaseController {
    @Autowired
    private TdeviceService service;

    @Autowired
    private Tdevice_recordService recordService;

    @Autowired
    private Twarn_recordService warn_recordService;
    @Autowired
    private Tnb_dev_jsonService tnb_dev_jsonService;

    @Autowired
    private Twarn_record_detailMapper twarn_record_detailMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(TDeviceController.class);

    @ResponseBody
    @RequestMapping("save")
    public String save(@RequestParam String bean) {
        try {

            MTdevice entity = JsonHelper.toBean(bean, MTdevice.class);

            if (entity.getDEVICE_ID() > 0) {
                service.update(entity);
            } else {
                entity.setSTATUS_ID(3);
                entity.setBDEL(1);
                service.insert(entity);

            }
            return LResult.Success(entity.getDEVICE_ID()).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("deviceUpOrDown")
    public String deviceUpOrDown(@RequestParam String bean, String empId, int flag, String memo) {
        try {
            MTdevice entity = JsonHelper.toBean(bean, MTdevice.class);

            if (entity.getDEVICE_ID() > 0) {
                if (flag == 1) {
                    entity.setSTATUS_ID(1);
                } else {
                    entity.setSTATUS_ID(4);
                }
                service.update(entity);
                MTdevice_record record = new MTdevice_record();
                if (flag == 1) {
                    record.setDESCS("设备上线 " + memo);
                } else {
                    record.setDESCS("设备下线 " + memo);
                }
                record.setSDATE(Common.toshortDate(Common.getNowDate()));
                record.setEMP_ID(Common.toInt(empId));
                record.setSTATUS_ID(1);
                record.setDEVICE_ID(entity.getDEVICE_ID());
                Date d = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                record.setCREATEDATE(Common.toLongDate(df.format(new Date())));
                recordService.insert(record);
            } else {
                throw new Exception("数据丢失为保存成功！");

            }
            return LResult.Success(entity.getDEVICE_ID()).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("get")
    public String getByid(@RequestParam Integer id) {
        try {
            //  String menu = request.getParameter("menu");
            MTdevice bean = service.single(id);
            return LResult.Success(bean).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("del")
    public String deleteByid(@RequestParam Integer id) {
        try {
            service.deleteById(id);
            return LResult.Success().toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("query")
    public String queryData() {

        try {
            PageData map = getPageData();
            if (!map.containsKey("appId")) {
                map.put("appId", 0);
            }
            if (!map.containsKey("sname")) {
                map.put("sname", "");
            }
            if (!map.containsKey("sdate")) {
                map.put("sdate", "");
            }
            if (!map.containsKey("edate")) {
                map.put("edate", "");
            } else {
                String strSdate = map.get("edate").toString();
                String tempdate = Common.getShortDate(Common.getSomeDay(strSdate, 1));
                map.put("edate", tempdate);
            }
            if (!map.containsKey("typeId")) {
                map.put("typeId", 0);
            }
            if (!map.containsKey("provinceId")) {
                map.put("provinceId", 0);
            }
            if (!map.containsKey("cityId")) {
                map.put("cityId", 0);
            }
            if (!map.containsKey("areaId")) {
                map.put("areaId", 0);
            }
            if (!map.containsKey("regionId")) {
                map.put("regionId", 0);
            }
            if (!map.containsKey("siteId")) {
                map.put("siteId", 0);
            }
            if (!map.containsKey("lineId")) {
                map.put("lineId", 0);
            }
            PageHelper.startPage(Common.toInt(map.get("page")), Common.toInt(map.get("limit")));
            List<Map<String, Object>> list = service.fetchByPage(map);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
            return LResult.Success(pageInfo.getTotal(), pageInfo.getList()).toJson();
        } catch (Exception ex) {
            return LResult.Error("数据错误").toJson();
        }
    }


    @ResponseBody
    @RequestMapping("getDeviceById")
    public String getDeviceById() {
        try {
            PageData map = getPageData();
            if (!map.containsKey("deviceId")) {
                throw new Exception("缺少必要参数！");
            }
            List<Map<String, Object>> list = service.getDeviceById(map);

            Integer count = list.size();
            return LResult.Success(count, list).toJson();
        } catch (Exception ex) {
            return LResult.Error("数据错误").toJson();
        }
    }

    @ResponseBody
    @RequestMapping("SaveDevice")
    public String SaveDevice() {
        try {

            PageData map = getPageData();
            if (!map.containsKey("typeId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("appId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("scaleId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("sname")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("protocolId")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("adcode")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("lat")) {
                throw new Exception("缺少必要参数！");
            }
            if (!map.containsKey("lon")) {
                throw new Exception("缺少必要参数！");
            }
            int id = service.Save(map);
            return LResult.Success(id).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("getAllDevice")
    public String getAllDevice() {
        try {
            PageData map = getPageData();
            if (!map.containsKey("appId")) {
                map.put("appId", 0);
            }
            if (!map.containsKey("userId")) {
                map.put("userId", 0);
            }
            if (!map.containsKey("lat")) {
//                map.put("lat", 40.620558);
                map.put("lat", "");
            }
            if (!map.containsKey("log")) {
//                map.put("log",109.832975);
                map.put("log", "");
            }

            int flag = Common.toInt(map.get("flag"));
            if (flag == 1) {
                List<Map<String, Object>> list = service.getAllDevice(map);
                Map<String, Object> resmap = new HashMap<>();
                resmap.put("list", list);
                MTapp mtapp = service.getTapp(Common.toInt(map.get("appId")));
                CenterPointAndZoom cp = new CenterPointAndZoom();
                cp.setLatitude(Common.toDouble(mtapp.getLAT()));
                cp.setLongitude(Common.toDouble(mtapp.getLNG()));
                cp.setZoom(15);
                resmap.put("cpz", cp);
                return LResult.Success(resmap).toJson();
            } else {
                Map<String, Object> resmap = service.getAllDevice1(map);
                return LResult.Success(resmap).toJson();
            }
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("getAllDevice1")
    public String getAllDevice1() {
        try {
            PageData map = getPageData();
            if (!map.containsKey("appId")) {
                map.put("appId", 0);
            }
            if (!map.containsKey("lat")) {
//                map.put("lat", 40.620558);
                map.put("lat", "");
            }
            if (!map.containsKey("log")) {
//                map.put("log",109.832975);
                map.put("log", "");
            }
            Map<String, Object> resmap = service.getAllDevice1(map);

            return LResult.Success(resmap).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("initList")
    public String initList() {
        try {
            Map<String, Object> map = service.initList();
            return LResult.Success(map).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("initEdit")
    public String initEdit(int appId) {
        try {
            Map<String, Object> map = service.initEdit(appId);
            return LResult.Success(map).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("initDeviceScaleById")
    public String initDeviceScaleById() {
        try {
            PageData param = getPageData();

            if (!param.containsKey("typeId")) {
                param.put("typeId", 0);
            }
            Map<String, Object> map = service.initDeviceScaleById(param);
            return LResult.Success(map).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("getDeviceImages")
    public String getDeviceImages() {
        try {
            //  String menu = request.getParameter("menu");
            PageData map = getPageData();

            PageHelper.startPage(Common.toInt(map.get("page")), Common.toInt(map.get("limit")));
            List<Map<String, Object>> list = service.getDeviceImages(map);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
            return LResult.Success(pageInfo.getTotal(), pageInfo.getList()).toJson();
        } catch (Exception ex) {
            return LResult.Error("数据错误").toJson();
        }
    }


    @ResponseBody
    @RequestMapping("saveDY")
    public String saveDY(@RequestParam String strJson) {
        try {
            //  String menu = request.getParameter("menu");


            List<MrecJG> list = JsonHelper.toList(strJson, MrecJG.class);
            String mid = "02";
            int mcode = 10;
            int wtypeId = 14;
            int deviceId = 39;
            String type = "电压";
            int sensorId = 8;
            for (MrecJG item :
                    list) {
                if (!item.getNodeOid().isEmpty()) {
                    List<MTdevice> list1 = service.fetch("AND IMEI=" + item.getNodeOid() + " ");
                    if (list1.size()<=0){
                        throw new  Exception("不存在此IMEI");
                    }
                    deviceId = list1.get(0).getDEVICE_ID();
                }


                String date=Common.getLongDate(item.getUpdateTime());
                int count = warn_recordService.getRecordCount("AND SDATE='" +date + "' AND DEVICE_ID="+deviceId+" AND WARN_TYPE_ID=" + wtypeId);
                if (count > 0) {
                    continue;
                }

                MTwarn_record model = new MTwarn_record();
                model.setDESCS(type + (item.getEventName() == "" ? "正常" : item.getEventName()) + item.getDValue());
                model.setWARN_TYPE_ID(wtypeId);
                model.setMESSAGEID(mid);
                Date dateStr = item.getUpdateTime();
                model.setSDATE(dateStr);
                model.setDEVICE_ID(deviceId);

//                MTnb_dev_json mjson = new MTnb_dev_json();
//                mjson.setIMEI(item.getNodeOid());
//                mjson.setMESSAGEID(mid);
//                mjson.setMESSAGETIME(dateStr);
//                mjson.setMEANCODE(mcode);
                MrecJson mstr = new MrecJson();
                mstr.setDValue(item.getDValue());
                mstr.setImei(item.getNodeOid());
                mstr.setMeanCode(mcode + "");
                mstr.setMessageId(mid);
                mstr.setMessageTime(dateStr);
                String tempJson = JsonHelper.toJson(mstr);
                model.setJSONSTR(tempJson);
                warn_recordService.insert(model);
                MTwarn_record_detail mTwarn_record_detail = new MTwarn_record_detail();
                mTwarn_record_detail.setDEVICE_ID(deviceId);
                if (item.getEventName() == "异常") {
                    mTwarn_record_detail.setWARN_TYPE_ID(wtypeId);
                    mTwarn_record_detail.setSTATUS("1");
                } else {
                    mTwarn_record_detail.setSTATUS("0");
                }
                mTwarn_record_detail.setSENSOR_ID(sensorId);
                mTwarn_record_detail.setVAL(item.getDValue());
                mTwarn_record_detail.setWARN_RECORD_ID(model.getWARN_ID());
                twarn_record_detailMapper.insert(mTwarn_record_detail);
//                mjson.setJOSNSTR(tempJson);
//                tnb_dev_jsonService.insert(mjson);
            }
            return LResult.Success("OK").toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("saveKG")
    public String saveKG(@RequestParam String strJson) {
        try {
            //  String menu = request.getParameter("menu");


            List<MrecJG> list = JsonHelper.toList(strJson, MrecJG.class);
            String mid = "02";
            int mcode = 1;
            int wtypeId = 13;
            int deviceId = 39;
            String type = "门磁正常开";
            int sensorId = 9;
            for (MrecJG item :
                    list) {
                if (!item.getNodeOid().isEmpty()) {
                    List<MTdevice> list1 = service.fetch("AND IMEI=" + item.getNodeOid() + " ");
                    if (list1.size()<=0){
                        throw new  Exception("不存在此IMEI");
                    }
                    deviceId = list1.get(0).getDEVICE_ID();
                }


                String date=Common.getLongDate(item.getUpdateTime());
                int count = warn_recordService.getRecordCount("AND SDATE='" +date + "' AND DEVICE_ID="+deviceId+" AND WARN_TYPE_ID=" + wtypeId);
                if (count > 0) {
                    continue;
                }
                MTwarn_record model = new MTwarn_record();
                model.setDESCS(type + (item.getEventName() == "" ? "正常" : item.getEventName()) + item.getDValue());
                model.setWARN_TYPE_ID(wtypeId);
                model.setMESSAGEID(mid);
                Date dateStr = item.getUpdateTime();
                model.setSDATE(dateStr);
                model.setDEVICE_ID(deviceId);


//                MTnb_dev_json mjson = new MTnb_dev_json();
//                mjson.setIMEI(item.getNodeOid());
//                mjson.setMESSAGEID(mid);
//                mjson.setMESSAGETIME(dateStr);
//                mjson.setMEANCODE(mcode);
                MrecJson mstr = new MrecJson();
                mstr.setDValue(item.getDValue());
                mstr.setImei(item.getNodeOid());
                mstr.setMeanCode(mcode + "");
                mstr.setMessageId(mid);
                mstr.setMessageTime(dateStr);
                String tempJson = JsonHelper.toJson(mstr);
                model.setJSONSTR(tempJson);
                warn_recordService.insert(model);
                MTwarn_record_detail mTwarn_record_detail = new MTwarn_record_detail();
                mTwarn_record_detail.setDEVICE_ID(deviceId);
                if (item.getEventName() == "异常") {
                    mTwarn_record_detail.setWARN_TYPE_ID(wtypeId);
                    mTwarn_record_detail.setSTATUS("1");
                } else {
                    mTwarn_record_detail.setSTATUS("0");
                }
                mTwarn_record_detail.setSENSOR_ID(sensorId);
                mTwarn_record_detail.setVAL(item.getDValue());
                mTwarn_record_detail.setWARN_RECORD_ID(model.getWARN_ID());
                twarn_record_detailMapper.insert(mTwarn_record_detail);


//                mjson.setJOSNSTR(tempJson);
//                tnb_dev_jsonService.insert(mjson);
            }
            return LResult.Success("OK").toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("saveXH")
    public String saveXH(@RequestParam String strJson) {
        try {
            //  String menu = request.getParameter("menu");


            List<MrecJG> list = JsonHelper.toList(strJson, MrecJG.class);
            String mid = "02";
            int mcode = 0;
            int wtypeId = 12;
            int deviceId = 39;
            String type = "信号";
            int sensorId = 11;
            for (MrecJG item :
                    list) {

                if (!item.getNodeOid().isEmpty()) {
                    List<MTdevice> list1 = service.fetch("AND IMEI=" + item.getNodeOid() + " ");
                    if (list1.size()<=0){
                        throw new  Exception("不存在此IMEI");
                    }
                    deviceId = list1.get(0).getDEVICE_ID();
                }


                String date=Common.getLongDate(item.getUpdateTime());
                int count = warn_recordService.getRecordCount("AND SDATE='" +date + "' AND DEVICE_ID="+deviceId+" AND WARN_TYPE_ID=" + wtypeId);
                if (count > 0) {
                    continue;
                }
                MTwarn_record model = new MTwarn_record();
                model.setDESCS(type + (item.getEventName() == "" ? "正常" : item.getEventName()) + item.getDValue());
                model.setWARN_TYPE_ID(wtypeId);
                model.setMESSAGEID(mid);
                Date dateStr = item.getUpdateTime();
                model.setSDATE(dateStr);
                model.setDEVICE_ID(deviceId);


//                MTnb_dev_json mjson = new MTnb_dev_json();
//                mjson.setIMEI(item.getNodeOid());
//                mjson.setMESSAGEID(mid);
//                mjson.setMESSAGETIME(dateStr);
//                mjson.setMEANCODE(mcode);
                MrecJson mstr = new MrecJson();
                mstr.setDValue(item.getDValue());
                mstr.setImei(item.getNodeOid());
                mstr.setMeanCode(mcode + "");
                mstr.setMessageId(mid);
                mstr.setMessageTime(dateStr);
                String tempJson = JsonHelper.toJson(mstr);
                model.setJSONSTR(tempJson);
                warn_recordService.insert(model);

                MTwarn_record_detail mTwarn_record_detail = new MTwarn_record_detail();
                mTwarn_record_detail.setDEVICE_ID(deviceId);
                if (item.getEventName() == "异常") {
                    mTwarn_record_detail.setWARN_TYPE_ID(wtypeId);
                    mTwarn_record_detail.setSTATUS("1");
                } else {
                    mTwarn_record_detail.setSTATUS("0");
                }
                mTwarn_record_detail.setSENSOR_ID(sensorId);
                mTwarn_record_detail.setVAL(item.getDValue());
                mTwarn_record_detail.setWARN_RECORD_ID(model.getWARN_ID());
                twarn_record_detailMapper.insert(mTwarn_record_detail);

//                mjson.setJOSNSTR(tempJson);
//                tnb_dev_jsonService.insert(mjson);
            }
            return LResult.Success("OK").toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }

    @ResponseBody
    @RequestMapping("saveYW")
    public String saveYW(@RequestParam String strJson) {
        try {
            //  String menu = request.getParameter("menu");


            List<MrecJG> list = JsonHelper.toList(strJson, MrecJG.class);
            String mid = "02";
            int mcode = 11;
            int wtypeId = 15;
            int deviceId = 39;
            String type = "液位";
            int sensorId = 10;
            for (MrecJG item :
                    list) {
                if (!item.getNodeOid().isEmpty()) {
                    List<MTdevice> list1 = service.fetch("AND IMEI=" + item.getNodeOid() + " ");
                    if (list1.size()<=0){
                        throw new  Exception("不存在此IMEI");
                    }
                    deviceId = list1.get(0).getDEVICE_ID();
                }
                String date=Common.getLongDate(item.getUpdateTime());
                int count = warn_recordService.getRecordCount("AND SDATE='" +date + "' AND DEVICE_ID="+deviceId+" AND WARN_TYPE_ID=" + wtypeId);
                if (count > 0) {
                    continue;
                }
                MTwarn_record model = new MTwarn_record();
                model.setDESCS(type + (item.getEventName() == "" ? "正常" : item.getEventName()) + item.getDValue());
                model.setWARN_TYPE_ID(wtypeId);
                model.setMESSAGEID(mid);
                Date dateStr = item.getUpdateTime();
                model.setSDATE(dateStr);
                model.setDEVICE_ID(deviceId);
                warn_recordService.insert(model);

//                MTnb_dev_json mjson = new MTnb_dev_json();
//                mjson.setIMEI(item.getNodeOid());
//                mjson.setMESSAGEID(mid);
//                mjson.setMESSAGETIME(dateStr);
//                mjson.setMEANCODE(mcode);
                MrecJson mstr = new MrecJson();
                mstr.setDValue(item.getDValue());
                mstr.setImei(item.getNodeOid());
                mstr.setMeanCode(mcode + "");
                mstr.setMessageId(mid);
                mstr.setMessageTime(dateStr);
                String tempJson = JsonHelper.toJson(mstr);
                model.setJSONSTR(tempJson);
                warn_recordService.insert(model);

                MTwarn_record_detail mTwarn_record_detail = new MTwarn_record_detail();
                mTwarn_record_detail.setDEVICE_ID(deviceId);
                if (item.getEventName() == "异常") {
                    mTwarn_record_detail.setWARN_TYPE_ID(wtypeId);
                    mTwarn_record_detail.setSTATUS("1");
                } else {
                    mTwarn_record_detail.setSTATUS("0");
                }
                mTwarn_record_detail.setSENSOR_ID(sensorId);
                mTwarn_record_detail.setVAL(item.getDValue());
                mTwarn_record_detail.setWARN_RECORD_ID(model.getWARN_ID());
                twarn_record_detailMapper.insert(mTwarn_record_detail);
//                mjson.setJOSNSTR(tempJson);
//                tnb_dev_jsonService.insert(mjson);
            }
            return LResult.Success("OK").toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }


    @ResponseBody
    @RequestMapping("getDeviceSensor")
    public String getDeviceSensor(int deviceId) {
        try {
            //
            List<Map<String, Object>> map = service.getDeviceSensor(deviceId);
            return LResult.Success(map).toJson();
        } catch (Exception ex) {
            return LResult.Error(ex.getMessage()).toJson();
        }
    }


}
